package com.easycoding.framework.util;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.File;
import java.text.SimpleDateFormat;
import java.text.ParseException;

import org.springframework.dao.DataIntegrityViolationException;



/** @pdOid df505e3e-f8a3-44a9-ba6b-f40f451c473c */
public class Tool {
    public static int MININT = -9999999; //最小整数
    public static long MINLONG = -9999999; //最小长整数
    public static double MINDOUBLE = -9999999; //最小整数
    public static float MINFLOAT = -9999999; //最小整数

    public static int toNumeric(String str) {
        if (str == null || str.trim().equals("")) {
            return MININT;
        } else {
            try {
                int tmpReturn = Integer.parseInt(str);
                return tmpReturn;
            } catch (Exception ex) {
                return MININT;
            }
        }
    }

    public static long toLong(String str) {
        if (str == null || str.trim().equals("")) {
            return MINLONG;
        } else {
            try {
                long tmpReturn = Long.parseLong(str);
                return tmpReturn;
            } catch (Exception ex) {
                return MINLONG;
            }
        }
    }

    public static double toDouble(String str){
        if (str == null || str.trim().equals("")) {
            return MINDOUBLE;
        } else {
            try {
                double tmpReturn = Double.parseDouble(str);
                return tmpReturn;
            } catch (Exception ex) {
                return MINDOUBLE;
            }
        }
    }

    public static float toFloat(String str){
        if (str == null || str.trim().equals("")) {
            return MINFLOAT;
        } else {
            try {
                float tmpReturn = Float.parseFloat(str);
                return tmpReturn;
            } catch (Exception ex) {
                return MINFLOAT;
            }
        }
    }

    public static boolean isNull(int num) {
       if(intToInt(num)==MININT) return true;
       return false;
    }

    public static boolean isEmpty(String str) {
        if (str == null || str.trim().equals("")) {
            return true;
        } else {
            return false;
        }
    }
    
    public static boolean isEmpty(Collection<?> collection) {
        if (collection == null || collection.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
    
    public static boolean isEmpty(Map<?, ?> map) {
        if (map == null || map.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
    
    public static boolean isEmpty(Object[] objs) {
        if (objs == null || objs.length == 0) {
            return true;
        } else {
            return false;
        }
    }

    public static int intToInt(int _tmint) {
        int rint = MININT;
        try {
            rint = _tmint;
        } catch (Exception ex) {}
        return rint;
    }

    /**
     * 把java.sql.Date类型时间转换为YYYY-MM-DD日期型
     * @param date java.sql.Date类型时间
     * @return String
     */
    public static String dateToString(java.sql.Date date) {
        java.util.Date ud = null;
        String strDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ud = sqlToUtil(date);
        strDate = sdf.format(ud);
        return strDate;
    }

    public static java.sql.Date stringToDate(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date ud = null;
        java.sql.Date sd = null;
        try {
            ud = sdf.parse(date);
        } catch (ParseException pe) {
            //System.err.print("执行FormatTime.stringToDate方法出错: " + pe.toString());
        }
        sd = utilToSql(ud);
        return sd;
    }

    /**
     * 把java.util.Date转化成java.sql.Date
     * @param ud java.util.Date的实例
     * @return java.sql.Date的实例
     */
    public static java.sql.Date utilToSql(java.util.Date ud) {
        java.sql.Date sd;
        sd = new java.sql.Date(ud.getTime());
        return sd;
    }

    /**
     * 把java.sql.Date转化成java.util.Date
     * @param sd java.sql.Date的实例
     * @return java.util.Date的实例
     */
    public static java.util.Date sqlToUtil(java.sql.Date sd) {
        java.util.Date ud;
        ud = new java.util.Date(sd.getTime());
        return ud;
    }

    /**
     * velgnne 2005-2-17
     * 把java.util.Date类型时间转换为String
     * @param date java.sql.Date类型时间
     * @return String
     */
    public static String dateToString(java.util.Date date, String fmt) {
        String strDate = null;
        if (date == null) {
            return strDate;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(fmt);
        strDate = sdf.format(date);
        return strDate;
    }

    /**
     * velgnne 2005-2-17
     * 把String转换为java.util.Date日期型
     * @param date java.sql.Date类型时间
     * @return String
     */
    public static Date stringToDate(String str, String fmt) {
        Date date = null;
        if (str == null || str.trim().equals("")) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(fmt);
        try {
            date = sdf.parse(str.trim());
        } catch (Exception ex) {
            //System.out.println("String to Date Convert Error:" + ex.toString());
        }
        return date;
    }

    public static String addBr(String Content) {
        if (Content == null || Content.equals("")) {
            return Content;
        }
        String makeContent = new String();
        StringTokenizer strToken = new StringTokenizer(Content, "\n");
        while (strToken.hasMoreTokens()) {
            if (makeContent.length() == 0) {
                makeContent = makeContent + strToken.nextToken();
            } else {
                makeContent = makeContent + "<br>" + strToken.nextToken();
            }
        }
        return makeContent;
    }

    // 将传入日期算出所在当月第几周
    public static String monthTheWeek(Date date) {
        int year;
        int month;
        GregorianCalendar now = new GregorianCalendar();
        GregorianCalendar temp = new GregorianCalendar();
        temp.setTime(date);
        now.setTime(date);
        year = now.get(GregorianCalendar.YEAR);
        month = now.get(GregorianCalendar.MONTH) + 1;
        int inWeek = 1;
        temp.set(GregorianCalendar.DAY_OF_MONTH, 1);
        for (int i = 0; i < temp.getMaximum(GregorianCalendar.DAY_OF_MONTH); i++) {
            if (temp.get(GregorianCalendar.DAY_OF_WEEK) ==
                GregorianCalendar.SATURDAY) {
                if (now.after(temp)) {
                    ++inWeek;
                }
            }
            temp.add(GregorianCalendar.DAY_OF_MONTH, 1);
        }

        if (inWeek <= monthAllWeek(now.getTime())) {
            if (month <= 9) {
                return year + "-0" + month + "-" + inWeek;
            } else {
                return year + "-" + month + "-" + inWeek;
            }
        } else {
            ++month;
            if (month <= 9) {
                return year + "-0" + month + "-" + "1";
            } else {
                return year + "-" + month + "-" + "1";
            }
        }
    }

//输入日期得到当月有几个周六
    public static int monthAllWeek(Date date) {
        GregorianCalendar now = new GregorianCalendar();
        now.setTime(date);
        int WeekNum = 0;
        now.set(GregorianCalendar.DAY_OF_MONTH, 1);
        for (int i = 0; i < now.getMaximum(GregorianCalendar.DAY_OF_MONTH); i++) {
            if (now.get(GregorianCalendar.DAY_OF_WEEK) ==
                GregorianCalendar.SATURDAY) {
                ++WeekNum;
            }
            now.add(GregorianCalendar.DAY_OF_MONTH, 1);
        }
        return WeekNum;
    }

//传入年月，当月第几周得到这周第一天的日期
    public static Date getWeekStart(int year, int month, int week) {
        String temp = year + "-" + month + "-" + "01";
        Date date = stringToDate(temp, "yyyy-MM-dd");
        --month;
        GregorianCalendar now = new GregorianCalendar();
        now.setTime(date);
        //System.out.println(Tools.dateToString(now.getTime(), "yyyy-MM-dd"));
        if (week <= monthAllWeek(now.getTime())) {
            now.set(GregorianCalendar.DAY_OF_WEEK, GregorianCalendar.MONDAY);
            //System.out.println(Tools.dateToString(now.getTime(), "yyyy-MM-dd"));
            now.add(GregorianCalendar.DAY_OF_MONTH, 7 * (week - 1));
            now.add(GregorianCalendar.DAY_OF_MONTH, -1);
            return now.getTime();
        } else {
            return null;
        }
    }

    //传入年月，当月第几周得到这周最后一天的日期
    public static Date getWeekEnd(int year, int month, int week) {
        String temp = year + "-" + month + "-" + "01";
        Date date = stringToDate(temp, "yyyy-MM-dd");
        --month;
        GregorianCalendar now = new GregorianCalendar();
        now.setTime(date);
        //System.out.println(Tools.dateToString(now.getTime(), "yyyy-MM-dd"));
        if (week <= monthAllWeek(now.getTime())) {
            now.set(GregorianCalendar.DAY_OF_WEEK, GregorianCalendar.SATURDAY);
            //System.out.println(Tools.dateToString(now.getTime(), "yyyy-MM-dd"));
            now.add(GregorianCalendar.DAY_OF_MONTH, 7 * (week - 1));
            return now.getTime();
        } else {
            return null;
        }
    }

    //传入日期输出上一周的周次
    public static String theBeforeWeek(Date thisDate) {
        GregorianCalendar temp = new GregorianCalendar();
        temp.setTime(thisDate);
        temp.add(GregorianCalendar.DAY_OF_MONTH, -7);
        return monthTheWeek(temp.getTime());
    }

    //传入月份返回上月月份
    public static String theBeforeMonth(String month) {
        Date d = stringToDate(month, "yyyy-MM");
        GregorianCalendar temp = new GregorianCalendar();
        temp.setTime(d);
        temp.add(GregorianCalendar.MONTH, -1);
        return dateToString(temp.getTime(), "yyyy-MM");
    }

    //根据最早,晚批示时间字段返回最早，晚批示时间日期值
    public static Date getEarlyPosDate(String earlyTime, Date today) {
        String tempa = earlyTime.substring(0, 1);
        String tempday = earlyTime.substring(2, 3);
        String temptime = earlyTime.substring(4, 6);
        String tempminute = earlyTime.substring(7, 9);
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(today);
        if (tempa.equals("1")) {
            gc.add(GregorianCalendar.DAY_OF_MONTH, 7);
        }
        gc.set(GregorianCalendar.DAY_OF_WEEK, Integer.parseInt(tempday));
        gc.set(GregorianCalendar.HOUR_OF_DAY, Integer.parseInt(temptime));
        gc.set(GregorianCalendar.MINUTE, Integer.parseInt(tempminute));
        return gc.getTime();
    }

    /**
     * 获得最早考勤时间
     * @return Date
     */
    public static Date getLogonEarlyTime(String early, String ymd) {
        String earlyest = ymd + " " + early;
        return stringToDate(earlyest, "yyyy-MM-dd HH:mm");
    }

    /**
     * 获取迟到时间
     * @return Date
     */
    public static Date getLogonLateTime(String start, String late, String ymd) {
        String temp = ymd + " " + start;
        Date date = stringToDate(temp, "yyyy-MM-dd HH:mm");
        GregorianCalendar now = new GregorianCalendar();
        now.setTime(date);
        now.add(GregorianCalendar.MINUTE, Integer.parseInt(late));
        return now.getTime();
    }

    /**
     * 获取允许迟到时间
     * @return Date
     */
    public static Date getLogonAllowTime(String start, String allow, String ymd) {
        String temp = ymd + " " + start;
        Date date = stringToDate(temp, "yyyy-MM-dd HH:mm");
        GregorianCalendar now = new GregorianCalendar();
        now.setTime(date);
        now.add(GregorianCalendar.MINUTE, Integer.parseInt(allow));
        return now.getTime();
    }

    public static int getMonthAllDate(String month) {
        Date d = stringToDate(month, "yyyy-MM");
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(d);
        if (month.equals(dateToString(new Date(), "yyyy-MM"))) {
            return Integer.parseInt(dateToString(new Date(), "dd"));
        } else {
            return gc.getMaximum(GregorianCalendar.DAY_OF_MONTH);
        }
    }

    /**
     * getYear 获取日期的年
     *
     * @param date Date
     * @return int
     */
    public static int getYear(Date date){
        if(date!=null){
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            return calendar.get(Calendar.YEAR);
        }
        return -1;
    }

    /**
     * getYear 获取日期的年
     *
     * @param date Date
     * @return int
     */
    public static int getMonth(Date date){
        if(date!=null){
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            return calendar.get(Calendar.MONTH);
        }
        return -1;
    }

    /**
     * 计算两时间间隔
     * @param beginDate Date
     * @param endDate Date
     * @return int
     */
    public static int getEndDateToBeginDate(Date beginDate,Date endDate){
      if(beginDate==null||endDate==null){
        return 0;
      }
      String begin = dateToString(beginDate,"yyyy-MM-dd");
      String end = dateToString(endDate,"yyyy-MM-dd");
      long l_dis_day = ((long)(stringToDate(end,"yyyy-MM-dd").getTime()-stringToDate(begin,"yyyy-MM-dd").getTime()) / (3600 * 24 * 1000));
      return toNumeric(String.valueOf(l_dis_day));
    }

   
   /** @param encodeUrl
    * @pdOid 331b4958-92db-4f1c-9fa2-c6077b0cf213 */
   public static String encodeUrl(String encodeUrl) {
       if(encodeUrl!=null){
          encodeUrl = encodeUrl.replaceAll("\\?", "%3F");
          encodeUrl = encodeUrl.replaceAll("\\&", "%26");
          encodeUrl = encodeUrl.replaceAll("\\:", "%3A");
          encodeUrl = encodeUrl.replaceAll("\\/", "%2F");
          return encodeUrl;
       }
       return encodeUrl;
   }
   
   /** @param decodeUrl
    * @pdOid c2b53c70-4846-4733-8971-9e2e2bceb44f */
   public static String decodeUrl(String decodeUrl) {
       if(decodeUrl!=null){
           decodeUrl = decodeUrl.replaceAll("%3F", "\\?");
           decodeUrl = decodeUrl.replaceAll("%26", "\\&");
           decodeUrl = decodeUrl.replaceAll("%3A", "\\:");
           decodeUrl = decodeUrl.replaceAll("%2F", "\\/");
           return decodeUrl;
       }
       return decodeUrl;
   }
   
   /** @param url
    * @pdOid d21fcd97-1eac-4fc0-b473-73bb4e1caf32 */
   public static boolean containIM(String url) {
       if (url != null) {
           return url.indexOf("?") >= 0;
       }
       return false;
   }
   
   /** @param url
    * @pdOid cb29fcbd-f09c-4975-8841-6a013f600f28 */
   public static String getPreChar(String url)   {
         if (url != null) {
             return containIM(url) ? "&" : "?";
         }
         return "?";
   }
   
	/**
	 * 树组转化为ArrayList
	 * @param arrayKey
	 * @return
	 */	
	public static ArrayList<String> arrayToArrayList(String[] array){
		ArrayList<String> aList=new ArrayList<String>();
		for(int i=0;i<array.length;i++){
			aList.add(array[i]);
		}
		return aList;
	}
	
	
	public static String arrayListToStr(ArrayList<?> list){
		String str="";
		String temp="";
		if(list==null)return "";
		Iterator<?> ite=list.iterator();
		while(ite.hasNext()){
			temp=ite.next().toString();
			if(!isEmpty(temp))str+=temp+",";
		}
		return str;
	}
	
	/**
	 * 字符串转化为ArrayList
	 * @param str
	 * @param splitSign
	 * @return
	 */
	public static ArrayList<String> strToList(String str,String splitSign){
		ArrayList<String> aList=new ArrayList<String>();
		if(isEmpty(str)) return aList;
		StringTokenizer st=new StringTokenizer(str,splitSign);
		String item="";
        while(st.hasMoreTokens()){
        	item=st.nextToken();
        	if(!isEmpty(item))aList.add(item);
        }
		return aList;
	}
	
	
	
	/**
	 * 把字符串转化成sql可查询的字符串
	 * @param str
	 * @return
	 */
	public static String strToQuery(String str){
		
		String parameterStr="";
		String splitStr="";
		StringTokenizer st=new StringTokenizer(str,",");						
		while(st.hasMoreTokens()){
			splitStr=st.nextToken();
			if(!Tool.isEmpty(splitStr))parameterStr+="'"+splitStr+"'"+",";
		}	
		if(Tool.isEmpty(parameterStr))return "";
		parameterStr=parameterStr.substring(0, parameterStr.length()-1);	
		return parameterStr;
		
	}  
   
	public static boolean isTimeOut(String dateTime) throws Exception{
		boolean bool=false;
		Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(2, -3);
        String s1=dateTime+" 00:00:00";
        String s2=Tool.dateToString(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
        java.text.DateFormat df=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Calendar c1=java.util.Calendar.getInstance();
        java.util.Calendar c2=java.util.Calendar.getInstance();
        try
        {
            c1.setTime(df.parse(s1));
            c2.setTime(df.parse(s2));
        }catch(java.text.ParseException e){
        	e.printStackTrace();
        	throw new DataIntegrityViolationException(e.getMessage()); 
        }
        int result=c1.compareTo(c2);
        if(result<0)
            bool=true;
        return bool;
	}
	
	/**
	 * 计算日期相差月份
	 * @param date1
	 * @param date2
	 * @return
	 * @throws ParseException
	 */
	public static int getMonthSpace(Date date1, Date date2){
		int result = 0;
		try
        {
			Calendar c1 = Calendar.getInstance();
			Calendar c2 = Calendar.getInstance();
			c1.setTime(date1);
			c2.setTime(date2);
			result = (c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR))*12+c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
        }catch(Exception e){
        	e.printStackTrace();
        }
		return result == 0 ? 0 : Math.abs(result);
	}
	
	/** 
     * 使用java正则表达式去掉多余的.与0 
     * @param s 
     * @return  
     */  
    public static String subZeroAndDot(String s){  
    	if(s != null){
	        if(s.indexOf(".") > 0){  
	            s = s.replaceAll("0+?$", "");//去掉多余的0  
	            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉  
	        }  
    	}
        return s;  
    } 
    
    /**
     * 日期加天数
     * @param date
     * @param day
     * @return
     */
    public static Date dateAddDay(Date date, int day){
    	Calendar calendar=Calendar.getInstance();   
    	calendar.setTime(date);
    	calendar.add(Calendar.DATE,day);//.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);//让日期加1
    	return calendar.getTime();
    }
    
    /**
     * 日期加分钟数
     * @param date
     * @param minute
     * @return
     */
    public static Date dateAddMinute(Date date, int minute){
    	Calendar calendar=Calendar.getInstance();   
    	calendar.setTime(date);
    	calendar.add(Calendar.MINUTE,minute);//.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);//让日期加1
    	return calendar.getTime();
    }
    
    /**
     * 日期加月份数
     * @param date
     * @param month
     * @return
     */
    public static Date dateAddMonth(Date date, int month){
    	Calendar calendar=Calendar.getInstance();   
    	calendar.setTime(date);
    	calendar.add(Calendar.MONTH,month);//.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);//让日期加1
    	return calendar.getTime();
    }
    
    /**
     * 日期加年份数
     * @param date
     * @param year
     * @return
     */
    public static Date dateAddYear(Date date, int year){
    	Calendar calendar=Calendar.getInstance();   
    	calendar.setTime(date);
    	calendar.add(Calendar.YEAR,year);//.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);//让日期加1
    	return calendar.getTime();
    }
    
    /**
     * 日期加小时数
     * @param date
     * @param day
     * @return
     */
    public static Date dateAddHour(Date date, int hour){
    	Calendar calendar=Calendar.getInstance();   
    	calendar.setTime(date);
    	calendar.add(Calendar.HOUR,hour);//.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);//让日期加1
    	return calendar.getTime();
    }
    
    /**
	 * 通过资源判断是否具有请求地址的访问权限
	 * @param resourceString 资源
	 * @param requestString 请求地址
	 * @return
	 */
	public static boolean compareResource(String resourceString, String requestString) {
		String requestStr = null;
		String requestParam = null;
		String resourceStr = null;
		String resourceParam = null;
		String requestParams[] = (String[]) null;
		String resourceParams[] = (String[]) null;
		if (requestString != null && resourceString != null) {
			requestString.replaceAll("\\.\\./", "/");
			resourceString.replaceAll("\\.\\./", "/");
			if (requestString.indexOf("?") >= 0) {
				requestStr = requestString.substring(0, requestString
						.indexOf("?"));
				if (requestString.indexOf("?") + 1 < requestString.length()) {
					requestParam = requestString.substring(requestString
							.indexOf("?") + 1);
					if (requestParam != null)
						requestParams = requestParam.split("&");
				}
			} else {
				requestStr = requestString;
			}
			if (resourceString.indexOf("?") >= 0) {
				resourceStr = resourceString.substring(0, resourceString
						.indexOf("?"));
				if (resourceString.indexOf("?") + 1 < resourceString.length()) {
					resourceParam = resourceString.substring(resourceString
							.indexOf("?") + 1);
					if (resourceParam != null)
						resourceParams = resourceParam.split("&");
				}
			} else {
				resourceStr = resourceString;
			}
			if (requestStr != null && resourceStr != null
					&& requestStr.endsWith(resourceStr)) {
				if (resourceParams == null || resourceParams.length <= 0)
					return true;
				if (requestParams != null && resourceParams.length > 0) {
					for (int i = 0; i < resourceParams.length; i++) {
						boolean find = false;
						for (int j = 0; j < requestParams.length; j++)
							if (resourceParams[i].equals(requestParams[j]))
								find = true;

						if (!find)
							return false;
					}

					return true;
				}
			}
		}
		return false;
	}
	
	public static void deleteAll(File file){	
		if(!file.exists()) return;
		if(file.isFile()){
			file.delete();	
			return;
		}	
		File[] files = file.listFiles();	  
	  	for(int i=0;i<files.length;i++){
	  		deleteAll(files[i]);
	  	}	
	  	file.delete();
	}
	
	public static String transformSolrMetacharactor(String input){  
		if(!isEmpty(input)){
	        StringBuffer sb = new StringBuffer();  
	        String regex = "[+\\-&|!(){}\\[\\]^\"~*?:(\\)]";  
	        Pattern pattern = Pattern.compile(regex);  
	        Matcher matcher = pattern.matcher(input);  
	        while(matcher.find()){  
	            matcher.appendReplacement(sb, "\\\\"+matcher.group());  
	        }  
	        matcher.appendTail(sb);  
	        return sb.toString();
		}
		return input;
    }
    
    public static void main(String[] args){
    	System.out.println(Tool.dateToString(dateAddMonth(Tool.stringToDate("2012-12-31", "yyyy-MM-dd"),-1),"yyyy-MM-dd HH:mm:ss"));
    }
}